package com.skyworthclub.competition.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.skyworthclub.competition.beans.Match;
import com.skyworthclub.competition.beans.Role;
import com.skyworthclub.competition.service.MatchService;
import com.skyworthclub.competition.service.RoleService;
import com.skyworthclub.competition.utils.web.DataValidateUtil;
import com.skyworthclub.competition.utils.web.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author li
 * @since 2018-10-15
 */
@Controller
@RequestMapping("/api/match")
public class MatchController {

    private final MatchService matchService;
    private final RoleService roleService;
    private static final String ADMIN = "admin";

    @Autowired
    public MatchController(MatchService matchService, RoleService roleService) {
        this.matchService = matchService;
        this.roleService = roleService;
    }


    /**
     * 分页查询
     */
    @GetMapping("/list/{pageNum}")
    public ResponseEntity<Map<String, Object>> matchPage(@PathVariable(value = "pageNum") Integer pageNum) {

        //查询数据
        Page<Match> selectPage = matchService.getPage(pageNum);
        Map<String, Object> map = new HashMap<>(4);
        map.put("pageObject", selectPage);
        //成功返回
        return ResponseUtil.querySuccessResponse(map);
    }


    /**
     * 获取比赛详细情况
     *
     * @param matchId 比赛id
     */
    @GetMapping("/detail/{matchId}")
    public ResponseEntity<Map<String, Object>> matchDetail(@PathVariable("matchId") Integer matchId, HttpServletRequest request) {
        Match match = matchService.selectOne(matchId);

        // 未审核或审核不通过
        if (match.getIsChecked() != 1) {

            Map<String, Object> map = new HashMap<>(4);

            if (request.getUserPrincipal() != null) {
                String username = request.getUserPrincipal().getName();

                if (match.getMatchPublisher().equals(username)) {
                    map.put("match", match);
                    return ResponseUtil.querySuccessResponse(map);
                }

                List<Role> roles = roleService.getRolesByUserName(username);
                for (Role role : roles) {
                    if (ADMIN.equals(role.getRoleName())) {
                        map.put("match", match);
                        return ResponseUtil.querySuccessResponse(map);
                    }
                }
            }

            map.put("match", null);
            return ResponseUtil.querySuccessResponse(map);
        } else {
            Map<String, Object> map = new HashMap<>(4);
            map.put("match", match);
            return ResponseUtil.querySuccessResponse(map);
        }

    }

    @PostMapping("/post")
    public ResponseEntity<Map<String, Object>> addMatch(@RequestBody @Valid Match match,
                                                        Errors errors,
                                                        Principal principal) {
        //数据校验
        ResponseEntity<Map<String, Object>> responseEntity = DataValidateUtil.validate(errors);
        if (responseEntity != null) {
            return responseEntity;
        }
        //设置比赛发布者属性
        match.setMatchPublisher(principal.getName());
        boolean insert = matchService.insertOne(match);
        Map<String, Object> map = new HashMap<>(4);
        //添加成功
        if (insert) {
            match.setLogicFlag(1);
            map.put("match", match);
            return ResponseUtil.putSuccessResponse(map);
        }
        //添加失败
        map.put("matchId", -1);
        return ResponseUtil.putFailureResponse(map);
    }

    @PutMapping("/edit/{username}/{matchId}")
    public ResponseEntity<Map<String, Object>> editMatch(@PathVariable String username,
                                                         @PathVariable Integer matchId,
                                                         @RequestBody Match match,
                                                         Principal principal) {
        Map<String, Object> map = new HashMap<>(4);

        //安全校验
        if (!username.equals(principal.getName())) {
            map.put("error", "您没有访问权限！");
            return ResponseUtil.updateFailureResponse(map);
        }

        match.setMatchId(matchId);
        boolean update = matchService.updateMatchById(match);
        if (update) {
            return ResponseUtil.updateSuccessResponse(map);
        } else {
            return ResponseUtil.updateFailureResponse(map);
        }
    }


    @DeleteMapping("/delete/{matchId}")
    public ResponseEntity<Map<String, Object>> deleteMatch(@PathVariable Integer matchId,
                                                           HttpServletRequest request) {
        String username = request.getUserPrincipal().getName();
        Map<String, Object> map = new HashMap<>(4);
        boolean delete = matchService.deleteById(matchId, username);
        if (delete) {
            return ResponseUtil.deleteSuccessResponse(map);
        } else {
            return ResponseUtil.deleteFailureResponse(map);
        }
    }

    /**
     * 轮播图
     */
    @GetMapping("/carouselFigure")
    public ResponseEntity<Map<String, Object>> getCarouselFigure() {
        List<Match> matches = matchService.selectCarouselFigure();
        Map<String, Object> map = new HashMap<>(4);
        map.put("matches", matches);
        return ResponseUtil.querySuccessResponse(map);
    }

    /**
     * 按比赛类型分页查询：0比赛 1考证
     */
    @GetMapping("/list/type/{pageNum}")
    public ResponseEntity<Map<String, Object>> getMatchPageByType(@RequestParam(value = "matchType") Integer matchType,
                                                                  @PathVariable(value = "pageNum") Integer pageNum) {

        //查询数据
        Page<Match> selectPage = matchService.getPageByType(pageNum,matchType);
        Map<String, Object> map = new HashMap<>(4);
        map.put("pageObject", selectPage);
        //成功返回
        return ResponseUtil.querySuccessResponse(map);
    }

    /**
     * 按比赛等级分页查询：0国家级 1省级 2校级 3学院级
     */
    @GetMapping("/list/level/{pageNum}")
    public ResponseEntity<Map<String, Object>> getMatchPageByLevel(@RequestParam(value = "matchLevel") Integer matchLevel,
                                                                   @PathVariable(value = "pageNum") Integer pageNum) {

        //查询数据
        Page<Match> selectPage = matchService.getPageByLevel(pageNum,matchLevel);
        Map<String, Object> map = new HashMap<>(4);
        map.put("pageObject", selectPage);
        //成功返回
        return ResponseUtil.querySuccessResponse(map);
    }

}

